package com.peas.platform.module.icims.contract.basal.api;

import com.peas.platform.module.icims.contract.basal.dto.ContractTemplateDto;
import com.peas.platform.module.icims.contract.basal.service.ContractTemplateService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.poifs.filesystem.DirectoryEntry;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

@Api(tags = "自定义接口-[合同管理]合同模版")
@RestController
@RequestMapping("/api/v1/customContractTemplate")
@Slf4j
public class CustomContractTemplateController {

    @Resource
    private HttpServletRequest request;
    @Resource
    private HttpServletResponse response;
    @Resource
    private ContractTemplateService contractTemplateService;

    @SneakyThrows
    @ApiOperation(value = "合同模版下载")
    @GetMapping(value = "/download/{id}")
    public void download(@PathVariable(value = "id") Long id) {
        try {
            assert request != null;
            ContractTemplateDto template = contractTemplateService.getById(id);
            String fileName = "合同模版_" + template.getName() + ".doc";
            String name = URLEncoder.encode(fileName, StandardCharsets.UTF_8.name());
            //word内容
            String html = template.getContent();
            byte[] bs = html.getBytes(StandardCharsets.UTF_8);
            ByteArrayInputStream bais = new ByteArrayInputStream(bs);
            POIFSFileSystem poifs = new POIFSFileSystem();
            DirectoryEntry directory = poifs.getRoot();
            directory.createDocument("WordDocument", bais);
            //输出文件
            response.setHeader("Content-disposition", "attachment; filename=" + name);
            response.setCharacterEncoding(StandardCharsets.UTF_8.name());
            //response.setContentType("application/msword;charset=utf-8");//导出word格式
            response.setContentType("application/octet-stream;charset=utf-8");//导出word格式
            OutputStream os = response.getOutputStream();
            poifs.writeFilesystem(os);
            bais.close();
            os.close();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            response.setContentType(new MediaType(MediaType.APPLICATION_JSON, StandardCharsets.UTF_8).toString());
            throw e;
        }
    }

}
